package one.stand.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import one.stand.model.BusinessCardModel;
import one.stand.model.ResultModel;
import one.stand.model.UserModel;
import one.stand.model.VideoSwtichModel;
import one.stand.model.live.AttentionUserModel;
import one.stand.model.live.ShortVideoModel;
import one.stand.request.live.ShortVideoDataForm;
import one.stand.request.live.ShortVideoForm;
import one.stand.request.live.ShortVideoQuery;
import one.stand.request.live.SwitchVideoForm;
import one.stand.response.essay.EssayTypeResponse;
import one.stand.response.live.ShortVideoResponse;
import one.stand.service.BaseService;
import one.stand.service.ShortVideoService;
import one.stand.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author luoyang
 * @date 2020/5/20 11:52
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class ShortVideoServiceImpl extends BaseService implements ShortVideoService {


    @Autowired
    AttentionUserServiceImpl attentionUserService;

    @Override
    public ResultModel<Boolean> add(ShortVideoForm request) {
        if(request.getUserId() == null){
            request.setUserId(request.getId().intValue());
        }
        if(request.getCompanyId() == null){
            request.setCompanyId(request.getCId().intValue());
        }

        //检查公司上传视频数量限制,如果未设置则提示
        VideoSwtichModel videoSwtichModel = this.videoSwtichMapper.selectByCompanyId(request.getCompanyId().intValue());
        if(videoSwtichModel == null){
            return ResultModel.fail("未开通短视频上传权限,请联系管理员");
        }
        //查询当前公司拥有的视频数量
        final int size = this.shortVideoMapper.queryByCompanyId(request.getCompanyId().intValue());
        if(size > videoSwtichModel.getVideoSize() ){
            return ResultModel.fail("短视频上传数量超限,请联系管理员");
        }

        ShortVideoModel model = new ShortVideoModel();
        BeanUtils.copyProperties(request,model,getNullPropertyNames(request));
        model.setAttentionNum(0);
        model.setDeleted(0);
        model.setForwardNum(0);
        model.setGuestsNum(0);
        model.setLikesNum(0);
        model.setState(0);
        model.setPlayVolume(0);

        if(shortVideoMapper.insert(model) > 0){
            //发送消息给关注的用户
            sendUser(model);
            //添加公司默认的短视频开关
            addVideoSwtich(request);
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Async
    public void sendUser( ShortVideoModel model ){
        //查询当前已经关注的用户
        List<AttentionUserModel> attentionUserModelList = this.attentionUserMapper.queryByCompanyId(model.getCompanyId());
        if(attentionUserModelList != null){
            attentionUserModelList.forEach(userMode ->{
                this.attentionUserService.sendUserMsg(userMode.getUserId(),model.getCompanyId());
            });
        }
    }

    @Async
    public void addVideoSwtich(ShortVideoForm request){
        VideoSwtichModel videoSwtichModel = this.videoSwtichMapper.selectByCompanyId(request.getCompanyId());
        if(videoSwtichModel == null){
            videoSwtichModel = new VideoSwtichModel();
            videoSwtichModel.setCompanyId(request.getCompanyId());
            //默认为关闭
            videoSwtichModel.setState(false);
            videoSwtichModel.setCreateTime(DateUtil.now());
            this.videoSwtichMapper.insert(videoSwtichModel);
        }else{
            log.info("视频开关已经存在");
        }
    }

    @Override
    public ResultModel<Boolean> update(ShortVideoForm request) {
        ShortVideoModel oldModel = this.shortVideoMapper.queryById(request.getVideoId());
        if(oldModel == null){
            return ResultModel.fail("未找到短视频");
        }

        BeanUtils.copyProperties(request,oldModel,getNullPropertyNames(request));

        if(this.shortVideoMapper.update(oldModel) > 0){
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<ShortVideoResponse> queryById(ShortVideoQuery query) {
        ShortVideoModel oldModel = this.shortVideoMapper.queryById(query.getVideoId());
        if(oldModel == null){
            return ResultModel.fail("未找到短视频");
        }

        ShortVideoResponse response = new ShortVideoResponse();
        BeanUtils.copyProperties(oldModel,response);
        checkuserAttention(query,response);

        return ResultModel.success(response);
    }

    /**
     * 检查用户是否已关注，按名片用户计算
     * @param query
     * @param shortVideoResponse
     */
    private void checkuserAttention(ShortVideoQuery query,ShortVideoResponse shortVideoResponse){
        BusinessCardModel businessCardModel = this.businessCardMapper.queryUserById(shortVideoResponse.getUserId());

        shortVideoResponse.setUserName(Optional.ofNullable(businessCardModel).isPresent() ? businessCardModel.getName() : "");
        //是否关注
        if(query.getUserId() != null){
            AttentionUserModel userModel = this.attentionUserMapper.queryUserAndVideo(query.getUserId() == null ? query.getId().intValue() : query.getUserId(),shortVideoResponse.getVideoId(),query.getCompanyId().intValue());
            shortVideoResponse.setAttention(Optional.ofNullable(userModel).isPresent() ? userModel.getAttention() == null ? false : userModel.getAttention() == 1 ? true : false:  false);
            shortVideoResponse.setLike(Optional.ofNullable(userModel).isPresent() ? userModel.getIsLike() : false);
        }else{
            shortVideoResponse.setAttention(false);

        }
        //是否点赞
        shortVideoResponse.setLogo(Optional.ofNullable(businessCardModel).isPresent() ? businessCardModel.getAvatarUrl() : "");
        shortVideoResponse.setCardId(Optional.ofNullable(businessCardModel).isPresent() ? businessCardModel.getCardId() : 0);
    }

    @Override
    public ResultModel<PageInfo<ShortVideoResponse>> queryByList(ShortVideoQuery query) {
        if(query.getCompanyId() == null){
            query.setCompanyId(query.getCId().intValue());
        }

        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<ShortVideoModel> list = this.shortVideoMapper.queryAll(query);

        List<ShortVideoResponse> responses = new ArrayList<>();
        list.forEach( model -> {
            ShortVideoResponse shortVideoResponse = new ShortVideoResponse();
            BeanUtils.copyProperties(model,shortVideoResponse);
            checkuserAttention(query,shortVideoResponse);
            responses.add(shortVideoResponse);
        });

        PageInfo<ShortVideoResponse> pageInfo = new PageInfo(responses);

        return ResultModel.success(pageInfo);
    }

    @Override
    public ResultModel<Boolean> deleteById(Integer shortId) {
        if(this.shortVideoMapper.deleteById(shortId) > 0){
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Boolean> updateData(ShortVideoDataForm request) {
        ShortVideoModel oldModel = this.shortVideoMapper.queryById(request.getVideoId());
        if(oldModel == null){
            return ResultModel.fail("未找到短视频");
        }

        //按需修改
        if(request.getPlayVolume() != null){
            oldModel.setPlayVolume(oldModel.getPlayVolume() + 1);
        }

        if(request.getForwardNum() != null){
            oldModel.setForwardNum(oldModel.getForwardNum() + 1);
        }

        if(request.getIsLikes() != null){
            oldModel.setLikesNum(request.getIsLikes() ? oldModel.getLikesNum() + 1 : oldModel.getLikesNum() - 1 );
        }

        if(oldModel.getLikesNum() < 0){
            oldModel.setLikesNum(0);
        }

        if(request.getAttentionNum() != null){
            oldModel.setAttentionNum(oldModel.getAttentionNum() + 1);
        }

        if(request.getState() != null){
            oldModel.setState(request.getState());
        }

        if(this.shortVideoMapper.update(oldModel) > 0){
            return ResultModel.success();
        }
        return ResultModel.fail();
    }

    @Override
    public ResultModel<Boolean> switchVideo(SwitchVideoForm request) {
        VideoSwtichModel videoSwtichModel = this.videoSwtichMapper.selectByCompanyId(request.getCId().intValue());
        if(videoSwtichModel != null){
            videoSwtichModel.setState(request.getSwitchVideo());
            this.videoSwtichMapper.updateByPrimaryKey(videoSwtichModel);
            return ResultModel.success();
        }else{
            videoSwtichModel = new VideoSwtichModel();
            videoSwtichModel.setCompanyId(request.getCId().intValue());
            videoSwtichModel.setState(request.getSwitchVideo());
            videoSwtichModel.setCreateTime(DateUtil.now());
            this.videoSwtichMapper.insert(videoSwtichModel);
            return ResultModel.success();
        }
    }
}
